package com.xh.bussiness.tiku.controller;


import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.core.annotation.ExcludeLoginTokenIntercept;
import com.xh.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xh.bussiness.jingyou.service.IJYBaseDataService;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.tiku.bean.dto.BookChapterDto;
import com.xh.bussiness.tiku.bean.request.BookChapterRequest;
import com.xh.bussiness.tiku.model.BookChapter;
import com.xh.bussiness.tiku.model.BookVersion;
import com.xh.bussiness.tiku.service.IBookChapterService;
import com.xh.bussiness.tiku.service.IBookVersionService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 *
 * </p>
 *
 * @author Pitt zhang
 * @since 2019/3/4
 */
@Api(tags="教材章节接口")
@RestController
@RequestMapping("/tiku/bookChapter")
public class BookChapterController  extends BaseController {

    @Autowired
    private IBookChapterService bookChapterService;
    @Autowired
    private IJYBaseDataService baseDataService;
    
    /**
     * 分页查询
     */
    @ApiOperation(value = "教材章节分页查询", notes = "教材章节分页查询")
    @PostMapping("/queryPage")
    public XhPage queryPage(XhPage page, BookChapterRequest request) {
        return bookChapterService.queryBookChapterPage(page,request);
    }

    /**
     * 数据查询
     * @param request
     * @return
     */
    @ApiOperation(value="教材章节查询", notes = "教材章节查询")
    @PostMapping("/queryAll")
    public AjaxResult queryAll(BookChapterRequest request) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", bookChapterService.queryBookChapter(request));
    }


    /**
     * 新增和保存
     * @param bookChapterDto 实体对象
     * @return
     */
    @ApiOperation(value="教材章节保存", notes = "教材章节保存")
    @PostMapping(value="/saveOrUpdate")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(@Validated BookChapterDto bookChapterDto){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"", bookChapterService.saveOrUpate(bookChapterDto));
    }

    /**
     * 删除操作
     * @param id
     * @return
     */
    @ApiOperation(value="教材章节删除", notes = "教材章节删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id", value="教材章节id", required = true, dataType = "String"),
    })
    @PostMapping("/deleteById")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteById(String id){
        QueryWrapper qw = new QueryWrapper();
        qw.eq("parent_id", id);
        Integer count = bookChapterService.selectCount(qw);
        if (count > 0) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "该节点含有子节点，删除失败");
        }
        bookChapterService.delete(id);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 批量删除操作
     * @param ids
     * @return
     */
    @ApiOperation(value="教材章节批量删除", notes = "教材章节批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name="ids", value="教材章节id集合", required = true, dataType = "String[]"),
    })
    @PostMapping("/batchDelete")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult batchDelete(String[] ids){
        bookChapterService.batchDelete(ids);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }
    
    @ApiOperation(value="根据版本查询章节树")
    @ApiImplicitParams({
            @ApiImplicitParam(name="bookId", value="教材版本id", required = true, dataType = "String"),
    })
    @PostMapping("/queryTreeByBookVersion")
    public AjaxResult queryTreeByBookVersion(String bookId){
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, bookChapterService.queryBookChapterKnowledgeTree(bookId));
    }

    /**
     * 节点移动
     * @param bookChapterId 章节id
     * @param moveType -1：下移；1：上移
     * @return
     */
    @ExcludeLoginTokenIntercept
    @RequestMapping("/moveUpOrDownBookChapter")
    public AjaxResult moveUpOrDownBookChapter(String bookChapterId, Integer moveType) {
        return new AjaxResult(bookChapterService.moveUpOrDownBookChapter(bookChapterId, moveType));
    }


    @ApiOperation(value="教材章节初始化", notes = "教材章节初始化")
    @PostMapping("/initBookChapter")
    public AjaxResult initBookChapter() throws Exception{
    	List<Dictionary> data = baseDataService.querySubject();
    	List<BookChapter> chapters = new ArrayList<BookChapter>();
    	List<BookVersion> allBooks = new ArrayList<BookVersion>();
    	data.forEach(dic -> {
    		try {
    			List<BookVersion> books = baseDataService.queryBook(dic.getCode());
    			allBooks.addAll(books);
    			books.forEach(book -> {
    				if(book.getChilds()!=null){
    					chapters.addAll(book.getChilds());
    				}
    			});
			} catch (Exception e) {
				e.printStackTrace();
				allBooks.clear();
				chapters.clear();
			}
    	});
    	if(allBooks.isEmpty() || chapters.isEmpty()){
    		return new AjaxResult(AjaxResultConstant.Result.ERROR,"失败了");
    	}
    	// 插入本地库
//    	bookVersionService.truncateTable();
//    	bookVersionService.batchInsert(allBooks);
//    	bookChapterService.truncateTable();
//    	bookChapterService.batchInsert(chapters);
        bookChapterService.initBookChapterKnowledgeRelation(chapters);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,"成功了");
    }
    
}
